(ns blade-art-online.user
  (:require [ring.util.response :refer [response]]
            [clojure.string :as str]
            [blade-art-online.db.user :as users]))


(defn uri-match? [url]
  (str/starts-with? url "/user"))

(defn uri-without-prefix [uri]
  (subs uri 5))

(defn register-uri-match? [uri]
  (str/starts-with? uri "/register"))

(defn login-uri-match? [uri]
  (str/starts-with? uri "/login"))

(defn session-login [res]
  (assoc res :session {:login true}))

(defn handle-register [request register]
  (let [name (get-in request [:bodys :name])
        pass (get-in request [:bodys :pass])] 

       (try
         (register {:name name :pass pass})
         (response {:ok true})

       (catch Exception e
         (response {:ok false 
                    :msg (str "Register error: " (.getMessage e))})))))

(defn handle-login [request user-exist?]
  (let [name (get-in request [:bodys :name])
        pass (get-in request [:bodys :pass])] 

       (try 

         (if (user-exist? {:name name :pass pass})
           (-> {:ok true}
               (response)
               (session-login))
           (response {:ok false :msg "Login error: no this user"}))

         (catch Exception e
           (response {:ok false
                      :msg (str "Login error: " (.getMessage e))})))))

(defn handle 

 ([request] (handle request users/insert-user users/user-exist?))

 ([{uri :uri :as request} register user-exist?]
  (let [uri (uri-without-prefix uri)]
    (cond

      (register-uri-match? uri) (handle-register request register)

      (login-uri-match? uri) (handle-login request user-exist?)

      :else (response {:ok false :msg "User controller hasnt this uri!"})))))
